package com.schedule.controller.admin;


import com.schedule.daoVo.LoginVo;
import com.schedule.dto.LoginDto;
import com.schedule.entity.LoginUser;
import com.schedule.exception.MessageConstant;
import com.schedule.properties.JwtProperties;
import com.schedule.result.Result;
import com.schedule.server.AdminServer;
import com.schedule.utils.JwtUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;


/**
 * 用户及管理员的登录
 */
@Slf4j
@RestController
@RequestMapping("/admin")
@Tag(name = "登录面板")
public class AdminController {
    @Autowired
    private AdminServer adminServer;

    @Autowired
    private JwtProperties jwtProperties;


    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result<LoginVo> login(@RequestBody LoginDto loginDto) {
        LoginUser loginUser = adminServer.Login(loginDto);
        log.info("登录的参数{}", loginDto);
        Map<String, Object> claims = new HashMap<>();
        claims.put("nickname", loginUser.getNickname());
        claims.put("id", loginUser.getId());
    try {
        String token = JwtUtil.create_Jwt(
                jwtProperties.getSecretKey(),
                jwtProperties.getTtlMills(),
                claims
        );
        log.info("登录成功的{}", token);

        LoginVo loginVo = LoginVo.builder()
                .id(loginUser.getId())
                .name(loginUser.getNickname())
                .userName(loginUser.getUsername())
                .token(token)
                .build();
        return Result.success(loginVo);
    } catch (Exception e) {
            log.warn("登录失败：{}", e.getMessage());
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }

    }


    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public Result register(@RequestBody LoginDto registerData){
        adminServer.Regiser(registerData);
        return Result.success(MessageConstant.USER_REGISER);
    }

}
